package com.cbgolf.oa.activity.message;

import static com.cbgolf.oa.util.AnimaUtil.stopLoading;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.cbgolf.oa.R;
import com.cbgolf.oa.base.BaseActivity;
import com.cbgolf.oa.entity.IdNameBean;
import com.cbgolf.oa.entity.NetResponse;
import com.cbgolf.oa.inteface.INetCallBack;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.DialogUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.widget.datechoose.DateChooseWheelViewDialog;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * Created by lq on 2017/9/1.
 */

public class MessageActivity extends BaseActivity {

    //top
    @ViewInject(R.id.topBack_ll)
    private View topBack;
    @ViewInject(R.id.title_tv)
    private TextView topTitle;
    @ViewInject(R.id.topRight_iv)
    private ImageView topRightIv;
    //body
    @ViewInject(R.id.a_message_im_ll)
    private View imView;
    @ViewInject(R.id.a_message_im_cb)
    private CheckBox imCb;
    @ViewInject(R.id.a_message_timed_ll)
    private View timedView;
    @ViewInject(R.id.a_message_timed_cb)
    private CheckBox timedCb;
    @ViewInject(R.id.a_message_time_tv)
    private TextView timeTv;
    //
    @ViewInject(R.id.a_message_male_ll)
    private View maleView;
    @ViewInject(R.id.a_message_male_cb)
    private CheckBox maleCb;
    @ViewInject(R.id.a_message_female_ll)
    private View femaleView;
    @ViewInject(R.id.a_message_female_cb)
    private CheckBox femaleCb;
    //
    @ViewInject(R.id.a_message_visitor_ll)
    private View visitorView;
    @ViewInject(R.id.a_message_visitor_cb)
    private CheckBox visitorCb;
    @ViewInject(R.id.a_message_vip_ll)
    private View vipView;
    @ViewInject(R.id.a_message_vip_cb)
    private CheckBox vipCb;
    @ViewInject(R.id.a_message_chuzhi_ll)
    private View storedView;
    @ViewInject(R.id.a_message_chuzhi_cb)
    private CheckBox storedCb;
    //
    @ViewInject(R.id.a_message_et)
    private EditText msgEt;
    //
    @ViewInject(R.id.a_message_submit_tv)
    private TextView subMitTv;

    //var
    private long sendTime = -1;
    private String pushType;
    private String gender;
    private String userType = "";
    private List<String> listUserType = new ArrayList<>();
    private boolean isEdit;
    private String msgId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_message);
    }

    @Override
    protected void findViews() {
        x.view().inject(this);
    }

    @Override
    protected void setViews() {
        topTitle.setText("消息推送");
        topRightIv.setVisibility(View.VISIBLE);
        topRightIv.setImageResource(R.drawable.jilu);
        Intent intent = getIntent();
        if (null != intent) {
            String msg = intent.hasExtra("msg") ? intent.getStringExtra("msg") : "";
            isEdit = intent.hasExtra("isEdit") ? intent.getBooleanExtra("isEdit", false) : false;
            msgId = intent.hasExtra("id") ? intent.getStringExtra("id") : "";
            if (!Util.isNull(msg)) {
                msgEt.setText(msg);
            }
        }
    }


    @Override
    protected void setListener() {
        topBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        topRightIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mStartActivity(PushHistoryActivity.class);
            }
        });
        imView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imCb.isChecked()) {
                    return;
                }
                imCb.setChecked(true);
                timedCb.setChecked(false);
                timeTv.setText("");
                sendTime = -1;
            }
        });
        timedView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (timedCb.isChecked()) {
                    return;
                }
                timedCb.setChecked(true);
                imCb.setChecked(false);
                timeTv.setText(DateUtil.stampToDate(System.currentTimeMillis() + "", "yyyy/MM/dd HH:mm:ss"));
                sendTime = System.currentTimeMillis();
            }
        });
        timeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateChooseWheelViewDialog startDateChooseDialog
                        = new DateChooseWheelViewDialog(context, new DateChooseWheelViewDialog.DateChooseInterface() {
                    @Override
                    public void getDateTime(String time, boolean longTimeChecked) {
                        if (!Util.isNull(time)) {
                            timeTv.setText(time);
                            try {
                                sendTime = Long.parseLong(DateUtil.dateToStamp(time, DateUtil.formatYMDHm));
                            } catch (Exception e) {
                            }
                        }
                    }
                });
//                startDateChooseDialog.setDateDialogTitle("击球时间");
                startDateChooseDialog.showDateChooseDialog();
            }
        });
        maleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                maleCb.toggle();
            }
        });
        femaleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                femaleCb.toggle();
            }
        });
        visitorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                visitorCb.toggle();
            }
        });
        vipView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vipCb.toggle();
            }
        });
        storedView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                storedCb.toggle();
            }
        });
        subMitTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkInfo();
            }
        });
    }


    private void checkInfo() {
        if (!Util.isNetWorkConnected()) {
            Util.showNoNet();
            return;
        }
        if (!maleCb.isChecked() && !femaleCb.isChecked()) {
            Util.show("请选择用户性别");
            return;
        }
        if (!visitorCb.isChecked() && !vipCb.isChecked() && !storedCb.isChecked()) {
            Util.show("请选择用户身份");
            return;
        }
        final String msg = msgEt.getText().toString().trim();
        if (Util.isNull(msg)) {
            Util.show("请输入消息内容");
            return;
        }

        if (!isEdit) {
            String title = "确认发送";
            String content = "您是否确认要发布消息？";
            DialogUtil.showMsgDialog(context, title, content, new DialogUtil.onSubmitListener() {
                @Override
                public void doSubmit() {
                    sendMessage(msg);
                }
            });
        } else {
            editMsg(msg);
        }


    }

    private void editMsg(final String mMessage) {
        String url = WebAPI.msg_edit_put + "/" + msgId;
        JSONObject map = new JSONObject();
        JSONArray array = new JSONArray();
        try {
            if (!maleCb.isChecked() || !femaleCb.isChecked()) {
                String gd = maleCb.isChecked() ? "MALE" : "FEMALE";
                gender = maleCb.isChecked() ? "男" : "女";
                map.put("gender", gd);
            } else {
                gender = "全部";
            }
            map.put("messageContent", mMessage);
            map.put("messageType", "SYSTEM");
            String pushTimeType = imCb.isChecked() ? "NOW" : "TIMING";
            pushType = imCb.isChecked() ? "即时推送" : "定时推送";
            map.put("pushTimeType", pushTimeType);
            if (-1 == sendTime) {
                sendTime = System.currentTimeMillis();
            }
            map.put("pushTime", sendTime);
            String storedId = "";
            listUserType.clear();
            if (visitorCb.isChecked()) {
                listUserType.add("访客");
                array.put(noVipId);
            }
            if (vipCb.isChecked()) {
                listUserType.add("会员");
                array.put(vipId);
            }
            if (storedCb.isChecked()) {
                storedId = "1";
                listUserType.add("储值储次用户");
                array.put(storedId);
            }
            map.put("identitys", array);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Map<String, Object> obj = new HashMap<>();
        obj.put("messageDto", map);
        String token = null == UserData.getUser() ? "" : UserData.getUser().getToken();
        obj.put("token", token);
        AnimaUtil.showLoading(context);
        Web.putjsonOk(url, obj, new NetCallBack(new INetCallBack() {
            @Override
            public void onResponse(NetResponse response) {
                stopLoading();
                if (200 != response.statusCode) {
                    Util.showNetError();
                    return;
                }
                Map<String, String> map = new HashMap<String, String>();
                map.put("pushType", pushType);
                if (-1 != sendTime) {
                    map.put("pushTime", DateUtil.stampToDate(String.valueOf(sendTime),
                            DateUtil.formatWithbias));
                }
                map.put("gender", gender);
                if (listUserType.size() == 3) {
                    userType = "所有用户";
                } else if (listUserType.size() > 0) {
                    for (int i = 0; i < listUserType.size(); i++) {
                        if (i < listUserType.size() - 1) {
                            userType += listUserType.get(i) + "、";
                        } else {
                            userType += listUserType.get(i);
                        }
                    }
                }
                map.put("userType", userType);
                map.put("msg", mMessage);
                mStartActivity(PushSuccessActivity.class, map);
                finish();
            }

        }));
    }


    private void sendMessage(final String mMessage) {
        String url = WebAPI.send_msg_post;
        JSONObject map = new JSONObject();
        JSONArray array = new JSONArray();
        JSONArray arrayNames = new JSONArray();
        try {
            if (!maleCb.isChecked() || !femaleCb.isChecked()) {
                String gd = maleCb.isChecked() ? "MALE" : "FEMALE";
                gender = maleCb.isChecked() ? "男" : "女";
                map.put("gender", gd);
            } else {
                gender = "全部";
            }
            map.put("messageContent", mMessage);
            map.put("messageType", "SYSTEM");
            String pushTimeType = imCb.isChecked() ? "NOW" : "TIMING";
            pushType = imCb.isChecked() ? "即时推送" : "定时推送";
            map.put("pushTimeType", pushTimeType);
            if (-1 == sendTime) {
                sendTime = System.currentTimeMillis();
            }
            map.put("pushTime", sendTime);
            String storedId = "";
            listUserType.clear();
            if (visitorCb.isChecked()) {
                listUserType.add("访客");
                arrayNames.put("访客");
                array.put(TextUtil.Text(noVipId));
            }
            if (vipCb.isChecked()) {
                listUserType.add("会员");
                arrayNames.put("会员");
                array.put(TextUtil.Text(vipId));
            }
            if (storedCb.isChecked()) {
                storedId = "1";
                listUserType.add("储值储次用户");
                arrayNames.put("储值储次用户");
                array.put(storedId);
            }
            map.put("identitys", array);
            map.put("identityNames", arrayNames);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Map<String, Object> obj = new HashMap<>();
        obj.put("messageDto", map);
        obj.put("token", DataUtil.getToken());
        AnimaUtil.showLoading(context);
        Web.postJsonOk(url, obj, new NetCallBack(new INetCallBack() {
            @Override
            public void onResponse(NetResponse response) {
                stopLoading();
                if (403 == response.statusCode) {
                    Util.show("没有推送权限");
                    return;
                }
                if (200 != response.statusCode) {
                    Util.show(response.errorMsg);
                    return;
                }
                Map<String, String> map = new HashMap<String, String>();
                map.put("pushType", pushType);
                if (-1 != sendTime) {
                    map.put("pushTime", DateUtil.stampToDate(String.valueOf(sendTime),
                            DateUtil.formatWithbias));
                }
                map.put("gender", gender);
                if (listUserType.size() == 3) {
                    userType = "所有用户";
                } else if (listUserType.size() > 0) {
                    for (int i = 0; i < listUserType.size(); i++) {
                        userType += ((i < listUserType.size() - 1) ? (listUserType.get(i) + "、")
                                : listUserType.get(i));
                    }
                }
                map.put("userType", userType);
                map.put("msg", mMessage);
                mStartActivity(PushSuccessActivity.class, map);
                finish();
            }

        }));

    }

    private String vipId;
    private String noVipId;
    private boolean vipOk;
    private boolean noVipOk;

    @Override
    protected void loadData() {
        super.loadData();
        String url = WebAPI.user_type_get;
        Map<String, String> map = new HashMap<>();
        String parkId = null == UserData.getUser() ? "" : UserData.getUser().getCourseId();
        String token = null == UserData.getUser() ? "" : UserData.getUser().getToken();
        map.put("courseId", parkId);
        map.put("identityType", "");
        map.put("pageSize", "9999999");
        map.put("currentPage", "0");
        map.put("token", token);
        AnimaUtil.showLoading(context);
        Web.getOK(url, map, new NetCallBack(new INetCallBack() {
            @Override
            public void onResponse(NetResponse response) {
                stopLoading();
                if (200 != response.statusCode || Util.isNull(response.result)) {
                    return;
                }
                List<IdNameBean> list = null;
                try {
                    com.alibaba.fastjson.JSONObject json = JSON.parseObject(response.result);
                    list = JSON.parseArray(json.getString("content"), IdNameBean.class);
                } catch (Exception e) {
                    return;
                }
                if (null != list && list.size() > 0) {
                    String name;
                    String id;
                    for (int i = 0; i < list.size(); i++) {
                        name = list.get(i).name;
                        id = list.get(i).id;
                        if (Util.isNull(name)) {
                            continue;
                        }
                        switch (name) {
                            case "访客":
                                noVipId = id;
                                noVipOk = true;
                                break;
                            case "会员":
                                vipId = id;
                                vipOk = true;
                                break;
                        }
                        if (vipOk && noVipOk) {
                            break;
                        }
                    }
                }
            }

        }));
    }
}
